package com.swiftride.service.impl;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.swiftride.constants.GlobalExceptionCode;
import com.swiftride.feign.DriverPointFeign;
import com.swiftride.feign.TencentDistanceFeign;
import com.swiftride.param.PointParam;
import com.swiftride.param.TencentDistanceParam;
import com.swiftride.result.R;
import com.swiftride.service.IOrderService;
import com.swiftride.utils.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@Service
public class TencentDistanceServiceImpl implements ITencentDistanceService {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private DriverPointFeign driverPointFeign;

    @Autowired
    private TencentDistanceFeign tencentDistanceFeign;

    @Override
    public void endDriving(String orderNo) {
        //3.业务实现
        //3.1 调用腾讯地图接口计算行驶总里程
        R<List<PointParam>> listR = driverPointFeign.selectByOrderNo(orderNo);
        AssertUtil.isTrue(listR.isSuccess(), GlobalExceptionCode.SERVICE_REQUEST_ERROR);

        List<PointParam> pointParamList = listR.getData();
        AssertUtil.isTrue(pointParamList != null && !pointParamList.isEmpty(), GlobalExceptionCode.DATA_EXCEPTION);

        calculateTotalDistance(orderNo, pointParamList);
    }

    public void calculateTotalDistance(String orderNo, List<PointParam> pointParamList) {
        int size = pointParamList.size();
        BigDecimal totalDistance = new BigDecimal(0);
        for (int i = 0; i < size - 1; i++) {
            PointParam curr = pointParamList.get(i);
            PointParam next = pointParamList.get(i + 1);

            TencentDistanceParam tencentDistanceParam = new TencentDistanceParam();
            tencentDistanceParam.setFrom(curr.getLatitude() + "," + curr.getLongitude());
            tencentDistanceParam.setTo(next.getLatitude() + "," + next.getLongitude());

            Object response = tencentDistanceFeign.calculateDistance(tencentDistanceParam);
            JSONObject responseObj = JSONUtil.parseObj(response);

            AssertUtil.isEquals(0, responseObj.getInt("status"), GlobalExceptionCode.SERVICE_REQUEST_ERROR);

            JSONObject resultObj = responseObj.getJSONObject("result");
            JSONObject firstRow = resultObj.getJSONArray("rows").getJSONObject(0);
            JSONObject firstElement = firstRow.getJSONArray("elements").getJSONObject(0);
            int distanceInMeters = firstElement.getInt("distance");

            BigDecimal distanceInKm = BigDecimal.valueOf(distanceInMeters)
                    .divide(BigDecimal.valueOf(1000), 2, RoundingMode.HALF_UP);
            totalDistance = totalDistance.add(distanceInKm);
        }
        orderService.endDriving(orderNo, totalDistance);
    }
}
